package cn.wenhe9.yygh.order.controller.api;

import cn.wenhe9.yygh.common.result.ResultResponse;
import cn.wenhe9.yygh.enums.PaymentStatusEnum;
import cn.wenhe9.yygh.order.service.PaymentService;
import cn.wenhe9.yygh.order.service.WeixinService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.Na;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author DuJinliang
 * 2022/4/8
 */
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {
    @Resource
    private WeixinService weixinService;

    @Resource
    private PaymentService paymentService;

    /**
     * 生成微信支付二维码
     * @param orderId Long
     * @return ResultResponse
     */
    @ApiOperation("生成微信支付二维码")
    @GetMapping("/createNative/{orderId}")
    public ResultResponse creatNative(@PathVariable(name = "orderId") Long orderId){
        Map map = weixinService.createNative(orderId);
        return ResultResponse.ok(map);
    }

    /**
     * 查询支付状态
     * @param orderId String
     * @return ResultResponse
     */
    @ApiOperation("查询支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public ResultResponse queryPayStatus(@PathVariable(name = "orderId") Long orderId){
        //调用微信接口实现支付状态查询
        Map<String, String> resultMap =  weixinService.queryPayStatus(orderId);
        //判断
        if (resultMap == null){
            return ResultResponse.fail().message("支付出错");
        }
        //支付成功
        if ("SUCCESS".equals(resultMap.get("trade_state"))){
            //更新订单状态
            String outTradeNo = resultMap.get("out_trade_no");
            paymentService.paySuccess(outTradeNo, resultMap);
            return ResultResponse.ok().message(PaymentStatusEnum.PAID.getName());
        }

        return ResultResponse.ok().message(PaymentStatusEnum.UNPAID.getName());
    }
}
